import fs from 'fs';
import path from 'path';
import readline from 'readline';
const _path = process.cwd();

// /plugins/违禁词/resources/prohibited/自定义.txt文件一行一条规则

// 违禁词库：https://github.com/fwwdn/sensitive-stop-words

export const rule = {
  prohibited: {
    reg: 'noCheck', //匹配消息正则，命令正则
    priority: 500, //优先级，越小优先度越高
    describe: '违禁词' //【命令】功能说明
  },
  addProhibited: {
    reg: '^#违禁词添加(.*)$', //匹配消息正则，命令正则
    priority: 50, //优先级，越小优先度越高
    describe: '违禁词添加' //【命令】功能说明
  },
  delProhibited: {
    reg: '^#违禁词删除(.*)$', //匹配消息正则，命令正则
    priority: 50, //优先级，越小优先度越高
    describe: '违禁词删除' //【命令】功能说明
  }
};

export function prohibited(e) {
  if (
    e.msg.content &&
    e.eventType === 'MESSAGE_CREATE' &&
    e.msg.content.indexOf('#违禁词添加') === -1 &&
    e.msg.content.indexOf('#违禁词删除') === -1
  ) {
    const files = fs.readdirSync(
      path.resolve(_path, './plugins/违禁词/resources/prohibited/')
    );
    // console.log(files);
    try {
      files.forEach(file => {
        // console.log(file);
        // console.log(path.extname(file));
        // let isProhibited = false;
        if (path.extname(file) === '.txt') {
          let rl = readline.createInterface({
            input: fs.createReadStream(
              path.resolve(
                _path,
                './plugins/违禁词/resources/prohibited/',
                file
              )
            )
          });
          let exist = [];
          rl.on('line', line => {
            if (line && line.trim() !== '') {
              if (e.msg.content.indexOf(line) !== -1) {
                exist.push(line);
              }
            }
          });
          rl.on('close', () => {
            if (exist.length > 0) {
              //  撤回消息
              client.messageApi
                .deleteMessage(e.msg.channel_id, e.msg.id, false)
                .then(res => {
                  // 禁言
                  client.muteApi
                    .muteMember(e.msg.guild_id, e.msg.author.id, {
                      seconds: 5 * 60 // 5分钟
                    })
                    .then(res => {
                      // 发警告
                      let message = {
                        content: `<@!${e.msg.author.id}> 请文明用语`
                      };
                      client.messageApi
                        .postMessage(e.msg.channel_id, message)
                        .catch(err => {
                          logger.error(err);
                        });
                    })
                    .catch(err => {
                      logger.error(err);
                    });
                })
                .catch(err => {
                  // 机器人权限不足，无法删除消息
                  logger.error('[违禁词]: 机器人权限不足，无法删除消息');
                  logger.error(err);
                });

              return true;
            }
          });
        }
      });
    } catch (e) {
      logger.error(e);
    }
  }
}
export async function addProhibited(e) {
  if (e.eventType === 'MESSAGE_CREATE') {
    let message = {};

    // 1	全体成员
    // 2	管理员
    // 4	群主/创建者
    // 5	子频道管理员
    // 没有权限
    if (
      !e.msg.member.roles.includes('4')
      // && !e.msg.member.roles.includes('5')
    ) {
      message = {
        content: `<@!${e.msg.author.id}> 无权限`,
        msg_id: e.msg.id
      };
      let { data } = await client.messageApi.postMessage(
        e.msg.channel_id,
        message
      );
      logger.info(data);
      return true;
    }
    if (e.msg.content) {
      // trim()去除前后空格
      let content = e.msg.content
        .replace('#违禁词添加', '')
        .replace(`<@!${bot.id}>`, '')
        .trim();
      if (content !== '') {
        let rl = readline.createInterface({
          input: fs.createReadStream(
            path.resolve(
              _path,
              './plugins/违禁词/resources/prohibited/',
              '自定义.txt'
            )
          )
        });
        let exist = [];
        rl.on('line', line => {
          if (line && line.trim() !== '') {
            if (line.trim() === content) {
              exist.push(line);
            }
          }
        });
        rl.on('close', () => {
          if (exist.length > 0) {
            message = {
              content: `违禁词已存在`,
              msg_id: e.msg.id
            };
          } else {
            // 写入自定义.txt
            fs.appendFileSync(
              path.resolve(
                _path,
                './plugins/违禁词/resources/prohibited/',
                '自定义.txt'
              ),
              content + '\n'
            );
            message = {
              content: `违禁词添加成功`,
              msg_id: e.msg.id
            };
          }
          client.messageApi
            .postMessage(e.msg.channel_id, message)
            .catch(err => {
              logger.error(err);
            });

          return true;
        });
      } else {
        message = {
          content: `违禁词不能为空`,
          msg_id: e.msg.id
        };
        let { data } = await client.messageApi.postMessage(
          e.msg.channel_id,
          message
        );
        logger.info(data);
        return true;
      }
    }
  } else {
    let message = {
      content: `请在子频道发送命令，如：#违禁词添加 违禁词`,
      msg_id: e.msg.id // 可选，消息id，如果指定则会回复该消息
    };
    const { data } = await client.directMessageApi.postDirectMessage(
      e.msg.guild_id,
      message
    );
    logger.info(data);
    return true;
  }
}
export async function delProhibited(e) {
  if (e.eventType === 'MESSAGE_CREATE') {
    let message = {};

    // 1	全体成员
    // 2	管理员
    // 4	群主/创建者
    // 5	子频道管理员
    // 没有权限
    if (
      !e.msg.member.roles.includes('4')
      // && !e.msg.member.roles.includes('5')
    ) {
      message = {
        content: `<@!${e.msg.author.id}> 无权限`,
        msg_id: e.msg.id
      };
      let { data } = await client.messageApi.postMessage(
        e.msg.channel_id,
        message
      );
      logger.info(data);
      return true;
    }

    if (e.msg.content) {
      // trim()去除前后空格
      let content = e.msg.content
        .replace('#违禁词删除', '')
        .replace(`<@!${bot.id}>`, '')
        .trim();
      if (content !== '') {
        const files = fs.readdirSync(
          path.resolve(_path, './plugins/违禁词/resources/prohibited/')
        );

        try {
          files.forEach(file => {
            if (path.extname(file) === '.txt') {
              let conn = '';
              fs.readFileSync(
                path.resolve(
                  _path,
                  './plugins/违禁词/resources/prohibited/',
                  file
                )
              )
                .toString()
                .split('\n')
                .forEach(line => {
                  // console.log(line);
                  if (line && line.trim() !== '') {
                    if (line.trim() !== content) {
                      conn += line + '\n';
                    }
                  }
                });
              fs.writeFileSync(
                path.resolve(
                  _path,
                  './plugins/违禁词/resources/prohibited/',
                  file
                ),
                conn
              );
            }
          });
          message = {
            content: `违禁词删除成功`,
            msg_id: e.msg.id
          };
          client.messageApi
            .postMessage(e.msg.channel_id, message)
            .catch(err => {
              logger.error(err);
            });
          return true;
        } catch (e) {
          logger.error(e);
        }
      } else {
        message = {
          content: `违禁词不能为空`,
          msg_id: e.msg.id
        };
        let { data } = await client.messageApi.postMessage(
          e.msg.channel_id,
          message
        );
        logger.info(data);
        return true;
      }
    }
  } else {
    let message = {
      content: `请在子频道发送命令，如：#违禁词添加 违禁词`,
      msg_id: e.msg.id // 可选，消息id，如果指定则会回复该消息
    };
    const { data } = await client.directMessageApi.postDirectMessage(
      e.msg.guild_id,
      message
    );
    logger.info(data);
    return true;
  }
}
